
/*
 * 总服务台，任务分发到对应的路由去实现
 */
const express = require('express')
const fs = require('fs')
const path = require('path')
const open = require('open')

const app = express()
const port = 2020
const localUrl = `http://localhost:${port}`

// 分发功能，依次导入 extension 目录下的内容
function dispathAcion() {
    let extensionPath = path.join(__dirname, 'extension')
    if (fs.existsSync(extensionPath)) {
        // 遍历目录，查询文件或文件夹
        let fileNames = fs.readdirSync(extensionPath)
        fileNames.forEach((item) => {
            let itemPath = `${extensionPath}/${item}`
            let stat = fs.statSync(itemPath);
            // 目录
            if (stat.isDirectory()) {
                let subExtention = require(itemPath)
                app.use(subExtention.path, subExtention.route)
            }
        })
    }
}

// 首页
app.get('/', (req, res) => {
    let filepath = path.resolve(__dirname, 'index.html')
    res.send(fs.readFileSync(filepath, 'utf-8'))
})

// 设置静态文件
app.use('/static', express.static(__dirname + '/public'))

dispathAcion()

app.listen(port)
console.log(`已启动服务：${localUrl}`)
open(localUrl)